package org.jeecg.modules.quartz.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.quartz.util.HttpUrls;
import org.jeecg.modules.quartz.util.SM3Utils;
import org.jeecg.modules.quartz.util.SymmetricEncoder;
import org.quartz.Job;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 同步SM2秘钥
 * @Author Scott
 */
@Slf4j
public class SyncSm2KeyJob implements Job {

    @Override
    public void execute(org.quartz.JobExecutionContext context) {
        log.info("同步SM2秘钥开始：");
        // 初始化参数
        String path = "http://172.30.199.2:10208/CertShare/refreshsecret";
        String accessId = "eeeeabfac4b54bbab0a67988f6928bfb";
        String accessToken = "19a381ea91fd43a99107fcbf36914972";
        String requestPath = "/CertShare/certBusinessLicenseAndHolder";
        String aesKey = accessId + "_" + requestPath;
        String sm3Sign = new SM3Utils().sm3(accessId + "#" + requestPath + "#" + accessToken);
        log.info("访问地址：" + path);
        // 封装参数
        Map<String, String> head = new HashMap<>();
        head.put("accessId", accessId);
        head.put("accessToken", accessToken);
        Map<String, String> data = new HashMap<>();
        data.put("requestPath", requestPath);
        data.put("sign", sm3Sign);
        Map<String, Object> params = new HashMap<>();
        params.put("head", head);
        params.put("data", data);
        log.info("参数params：" + params);
        // 调用动态刷新秘钥接口
        String response = HttpUrls.doPost(path, JSON.toJSONString(params));
        log.info("响应结果response：" + response);
        // 解密响应结果获取动态SM2私钥和私钥过期时间
        JSONObject bodys = JSONObject.parseObject(response);
        String datas = bodys.getString("data");
        if (!datas.isEmpty()){
            String dataStr = SymmetricEncoder.AESDncode(aesKey , datas);
            log.info("响应结果dataStr：" + dataStr);
            JSONObject dataJson = JSONObject.parseObject(dataStr);
            String privateKey = dataJson.getString("privateKey");
            String publicKey = dataJson.getString("publicKey");
            String expiredTime = dataJson.getString("expiredTime");
        }
        log.info("同步SM2秘钥结束。");
    }
}
